<?php
namespace App\Http\Controllers;

use App\Modules\User\Token;
use Illuminate\Http\Request;
use App\Services\User\UserIndex;

class AdapterWebController extends Controller
{

    # 请求token
    protected $request_token = null;

    /**
     * AdapterWebController constructor.
     */
    public function __construct(Request $request)
    {
        # 判断当前请求有没有token
        //$requestToken  = $request->cookie('request_token');
        $requestToken  = session('request_token');
        if (!$requestToken) {
            $psotData = (array) json_decode($request->input('textData', ''), TRUE);
            $psotData['token']  = $request->input('token', null);
            $token = app()->make(Token::class)->setPostData($psotData)->getToken();

            # 生成 token 失败
            if (SUCCESS_STATUS !== $token['status']){
                $exceptionData = auto_failure($token, '生成token失败');
                throw_exception('生成token失败', $exceptionData);
            }

            # 生成token
            $requestToken = $token['res']['token'];
            //setcookie('request_token', $token['res']['token'], time() + TOKEN_EXPIRE);
            session(['request_token'=>$requestToken]);
        }

        # 设置当前token
        $this->request_token = $requestToken;
    }

    /**
     * 执行应用层方法
     * @param $module
     * @param $action
     * @param array $execData
     * @param bool $throwException
     * @return array
     * @throws \App\Exceptions\RequestFailException
     */
    public function appLayerExec($module, $action, $execData = [], $throwException = true)
    {
        # 权限验证
        $p = strrpos($module,'\\');
        $res = substr($module,0,$p);
        //&& $res != 'App\Modules\Finance'
        if($module != 'App\Modules\Register\Register' && $res != 'App\Modules\Mobile' && $module != 'App\Modules\User\User'){
            $authCheck = UserIndex::Token()->checkAuths($this->request_token, $module . '@' . $action);
            if (SUCCESS_STATUS !== $authCheck['status']) {
                throw_exception('权限验证失败', $authCheck);
            }
        }
        # 调用返回应用层逻辑
        $execData['token']  = $this->request_token;
        $res = app()->make($module)->setPostData($execData)->$action();
        # 判断是否跑出异常
        if ($throwException && SUCCESS_STATUS !== $res['status']) {
            throw_exception($res['msg'], $res);
        }
        return $res;
    }

}
